from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from alipay import AliPay

from orders.models import OrderInfo
from .models import Payment


class AlipayView(APIView):
    def get(self, request, order_id):
        # 1.准备公钥私钥
        app_private_key_path = settings.APP_PRIVATE_KEY_PATH
        alipay_public_key_path = settings.ALIPAY_PUBLIC_KEY_PATH
        # 2.创建alipay对象
        alipay = AliPay(appid=settings.ALIPAY_APPID,
                        app_notify_url=None, # 默认回调url
                        app_private_key_path=app_private_key_path,
                        sign_type = 'RSA2',
                        debug = False,
                        alipay_public_key_path=alipay_public_key_path)
        # 3.生成字符订单编号
        # 电脑网站支付需要跳转https://openapi.alipaydev.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=999,
            subject='国际美多商城订单',
            return_url='http://www.meiduo.site:8080/pay_success.html'
        )
        # 4.返回支付页面
        alipay_url = settings.ALIPAY_GATEWAY + '?' +order_string

        return Response({'alipay_url': alipay_url})


class AlipayOrderStatusView(APIView):
    def put(self, request):
        # 1.获取参数
        data = request.query_params.dict()
        signature = data.pop('sign')
        # 2.校验参数
        app_private_key_path = settings.APP_PRIVATE_KEY_PATH
        alipay_public_key_path = settings.ALIPAY_PUBLIC_KEY_PATH

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=app_private_key_path,
            sign_type='RSA2',
            debug=False,
            alipay_public_key_path=alipay_public_key_path
        )
        success = alipay.verify(data, signature)
        if not success:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3.数据入库
        order_id = data.get('out_trade_no')
        trade_id = data.get('trade_no')
        Payment.objects.create(
            order_id=order_id,
            trade_id=trade_id
        )
        # 4.修改订单信息状态
        OrderInfo.objects.filter(order_id=order_id).update(
            status=OrderInfo.ORDER_STATUS_ENEM['UNSEND']
        )
        # 5.返回响应
        return Response({'trade_id': trade_id})


